package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.itheima.pojo.FeedbackVO;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.service.FeedbackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/feedback")
public class FeedbackController {

    @Autowired
    private FeedbackService feedbackService;

    @Autowired
    private UserService userService;

    /**
     * 分页+条件查询
     * @param feedbackVO
     * @return
     */
    @RequestMapping("/getList")
    public Map<String,Object> getList(@RequestBody FeedbackVO feedbackVO){
        PageInfo pageInfo = feedbackService.getList(feedbackVO);
        //封装返回数据
        Map<String,Object> result=new HashMap<>();
        result.put("code","success");
        //封装data
        Map<String,Object> data=new HashMap<>();
        //封装查询出的数据dataList
        List<Map> dataList=new ArrayList<>();
        List list = pageInfo.getList();
        for (Object o : list) {
            Map map = JSON.parseObject(JSON.toJSONString(o), Map.class);
            User user = userService.getUserByUid((String) map.get("userUid"));
            map.put("user",user);
            dataList.add(map);
        }
        data.put("records",dataList);
        data.put("total",pageInfo.getTotal());
        data.put("size",pageInfo.getSize());
        data.put("current",pageInfo.getPageNum());
        data.put("orders","");
        data.put("optimizeCountSql",true);
        data.put("isSearchCount",true);
        //将将data放入返回map
        result.put("data",data);

        return result;
    }

    /**
     * 删除选中
     * @param feedbackVOList
     */
    @RequestMapping("/deleteBatch")
    public Map<String,Object> deleteBatch(@RequestBody List<FeedbackVO> feedbackVOList){
        for (FeedbackVO feedbackVO : feedbackVOList) {
            feedbackService.deleteBatch(feedbackVO);
        }
        //封装返回对象
        Map<String,Object> result=new HashMap<>();
        result.put("code","success");
        result.put("data","删除成功");
        return result;
    }

    /**
     * 编辑
     * @param feedbackVO
     */
    @RequestMapping("/edit")
    public Map<String,Object> edit(@RequestBody FeedbackVO feedbackVO){
        feedbackService.edit(feedbackVO);
        Map<String,Object> result=new HashMap<>();
        result.put("code","success");
        result.put("data","更新成功");
        return result;
    }

}
